﻿using DotNetCore.CAP;
using Library.Core.Application.IInfrastructure.EntityFrameworkDataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Threading.Tasks;

namespace Library.Core.Infrastructure.EntityFrameworkDataAccess
{
    public abstract class TransactionBase<TContext> : ITransaction where TContext : DbContext
    {
        private IDbContextTransaction contextTransaction;
        private readonly TContext context;
        private readonly ICapPublisher _capPublisher;

        public TransactionBase(TContext context,ICapPublisher capPublisher)
        {
            this.context = context;
            _capPublisher = capPublisher;
        }
        public ITransaction BeginTransaction()
        {
            contextTransaction = context.Database.BeginTransaction(_capPublisher);
            return this;
        }
        public ITransaction BeginTransactionEF()
        {
            contextTransaction = context.Database.BeginTransaction();
            return this;
        }
        public ITransaction BeginTransactionEF(System.Data.IsolationLevel isolationLevel)
        {
            contextTransaction = context.Database.BeginTransaction(isolationLevel);
            return this;
        }
        public async Task<ITransaction> BeginTransactionEFAsync()
        {
            contextTransaction = await context.Database.BeginTransactionAsync();
            return this;
        }
        public async Task<ITransaction> BeginTransactionEFAsync(System.Data.IsolationLevel isolationLevel)
        {
            contextTransaction = await context.Database.BeginTransactionAsync(isolationLevel);
            return this;
        }


        public void Commit()
        {
            contextTransaction.Commit();
        }
        public async Task CommitAsync()
        {
            await contextTransaction.CommitAsync();
        }
        public void Dispose()
        {

        }
    }
}